import { queryCompanies } from '@/pages/SystemUser/service';
import { Role } from '@/utils/typings.d';
import { UploadOutlined } from '@ant-design/icons';
import { ModalForm, ProFormSelect, ProFormUploadButton } from '@ant-design/pro-form';
import { Button, message } from 'antd';
import type { RcFile } from 'antd/lib/upload';
import { useState } from 'react';
import { useModel } from 'umi';
import DownloadTemplate from './DownloadTemplate';

const MultiCreateSim = (props: { reload: () => void }) => {
  const { initialState } = useModel('@@initialState');
  const currUser = initialState?.currentUser;
  const role = currUser?.role;
  const [currOnwerId, setCurrOnwerId] = useState(currUser?.ownerId);
  const [visible, setVisible] = useState(false);
  return (
    <ModalForm
      modalProps={{
        destroyOnClose: true,
        onCancel: () => {
          setVisible(false);
        },
      }}
      layout="horizontal"
      labelCol={{ span: 6 }}
      wrapperCol={{ span: 16 }}
      width={600}
      title="批量添加流量卡"
      visible={visible}
      trigger={
        <Button onClick={() => setVisible(true)}>
          <UploadOutlined /> 批量添加流量卡
        </Button>
      }
      submitter={false}
    >
      {role === Role.ADMIN && (
        <ProFormSelect
          name="ownerId"
          label="归属公司"
          showSearch
          debounceTime={200}
          fieldProps={{
            onChange: (value) => {
              setCurrOnwerId(value);
            },
          }}
          rules={[{ required: true, message: '请选择流量卡所属' }]}
          placeholder="请选择流量卡所属公司(如未找到目标公司，请优先创建[企业管理者])"
          request={(val) => queryCompanies(val.keyWords, true)}
        />
      )}
      <ProFormUploadButton
        label="上传文件"
        title="xlsx格式，大小小于200K"
        name="create_multi"
        accept=".xlsx"
        action="/api/iot-sim/v1.0.0/file"
        fieldProps={{
          showUploadList: false,
          name: 'create_multi',
          data: {
            ownerId: currOnwerId,
          },
          beforeUpload: (file: RcFile): Promise<void> =>
            new Promise((resolve, rejects) => {
              const { name } = file;

              // .xlsx*表示匹配所有带有 .xlsx 的字段，$表示匹配字符串结尾位置
              const nameRegExp = new RegExp('.xlsx*$');
              const isXlsx = nameRegExp.test(name);

              if (!isXlsx) {
                message.error({
                  content: '文件类型错误, 请上传一个xlsx表格文件',
                  key: 'upload_iot',
                });
                rejects();
                return;
              }
              const isLt200K = file.size / 1024 < 200;
              if (!isLt200K) {
                message.error({
                  content: '文件过大，请上传一个小于200k的文件',
                  key: 'upload_iot',
                });
                rejects();
                return;
              }
              if (!currOnwerId) {
                message.error({ content: '获取用户所属公司失败', key: 'upload_iot' });
                rejects();
                return;
              }
              resolve();
            }),
        }}
        onChange={(info) => {
          const { status, response, name } = info.file;
          if (status === 'uploading') {
            message.loading({
              content: '文件处理中...',
              key: 'upload_info',
            });
          }
          if (status === 'done' && response?.code === 0) {
            message.success({
              content: response?.message || '上传成功',
              key: 'upload_info',
            });
            props.reload();
            setVisible(false);
            return true;
          }
          if (status === 'error' || (response?.code && response?.code !== 0)) {
            const msg = response?.message || '';
            message.error({ content: `${name}上传失败。${msg}`, key: 'upload_info' });
            return false;
          }
          return false;
        }}
      />
      <div
        style={{
          margin: '0 auto',
          width: '80%',
          padding: '15px 8px ',
          background: '#f4f6fa',
        }}
      >
        {role === Role.ADMIN && (
          <div style={{ fontWeight: 'bold', color: 'red' }}>
            系统管理员 请优先选择 「归属公司」 后再上传文件
          </div>
        )}
        <div>如果您没有批量模板文件，请点击下载：</div>

        <div style={{ margin: '5px 0' }}>
          <DownloadTemplate />
        </div>
        <div>使用excel编辑模板时，请确认输入的内容为文本格式。符号请在英文状态下输入。</div>
      </div>
    </ModalForm>
  );
};

export default MultiCreateSim;
